<script lang="ts" setup>
  import { GameRule, GameRuleItem } from '@/types/game';
  import { onMounted, ref } from 'vue';
  import { Form, Message } from '@arco-design/web-vue';
  import { createGameRule, updateGameRule } from '@/api/game-rule';

  const props = defineProps<{
    gameRule?: GameRule;
  }>();

  const emit = defineEmits(['close']);

  const formData = ref<{
    ruleTitle: string;
    ruleList: GameRuleItem[];
  }>({
    ruleTitle: '',
    ruleList: [],
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);

  const handleSubmit = async () => {
    if (formRef.value) {
      const validateResult = await formRef.value.validate();
      if (!validateResult) {
        saving.value = true;
        try {
          if (props.gameRule) {
            await updateGameRule({
              ...props.gameRule,
              ruleTitle: formData.value.ruleTitle,
              ruleDetail: JSON.stringify(formData.value.ruleList),
            });
          } else {
            await createGameRule({
              ruleTitle: formData.value.ruleTitle,
              ruleDetail: JSON.stringify(formData.value.ruleList),
            });
          }
          Message.success('操作成功');
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };

  const addItem = () => {
    formData.value.ruleList.push({
      title: '',
      content: '',
    });
  };

  const removeItem = (index: number) => {
    formData.value.ruleList.splice(index, 1);
  };

  onMounted(() => {
    if (props.gameRule) {
      formData.value.ruleTitle = props.gameRule.ruleTitle;
      formData.value.ruleList = JSON.parse(
        props.gameRule.ruleDetail
      ) as GameRuleItem[];
    }
  });
</script>

<template>
  <a-drawer
    :title="gameRule ? '编辑模板' : '新建模板'"
    :width="700"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formData" layout="vertical">
      <a-form-item
        label="规程名称"
        field="ruleTitle"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input v-model="formData.ruleTitle" />
      </a-form-item>

      <div class="container">
        <div class="list">
          <div
            v-for="(item, index) in formData.ruleList"
            :key="index"
            class="item"
          >
            <a-form-item
              hide-label
              :field="`ruleList[${index}].title`"
              :rules="[{ required: true, message: '不能为空' }]"
            >
              <a-input
                v-model="item.title"
                placeholder="规程标题"
                style="width: 300px"
              />
            </a-form-item>

            <a-form-item
              hide-label
              :field="`ruleList[${index}].content`"
              :rules="[{ required: true, message: '不能为空' }]"
            >
              <a-textarea
                v-model="item.content"
                placeholder="规程内容"
                style="width: 600px"
                :auto-size="{ minRows: 5 }"
              />
            </a-form-item>

            <a class="remove" @click="removeItem(index)">
              <icon-close-circle-fill />
            </a>
          </div>
        </div>
        <div class="add" @click="addItem"> <icon-plus />添加规程 </div>
      </div>
    </a-form>
  </a-drawer>
</template>

<style lang="less" scoped>
  .item {
    padding: 12px;
    border: 1px solid var(--color-border-2);
    border-radius: 3px;
    margin-bottom: 12px;
    position: relative;
  }
  .remove {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 10;
    color: rgb(var(--red-6));
    font-size: 18px;
    cursor: pointer;
    &:hover {
      color: rgb(var(--red-7));
    }
  }
  .add {
    border-radius: 3px;
    cursor: pointer;
    line-height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed var(--color-border-2);
    color: var(--color-text-3);
    &:hover {
      color: rgb(var(--primary-6));
      border-color: rgb(var(--primary-6));
    }
  }
</style>
